<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 导航栏 -->
    <van-nav-bar title="用户管理" fixed placeholder />

    <!-- 密码输入弹窗 -->
    <van-popup v-model:show="showKeyboard" position="bottom" :style="{ height: '40%' }">
      <div class="p-4">
        <div class="text-center mb-4">请输入4位数字密码</div>
        <div class="flex justify-center mb-4">
          <div class="grid grid-cols-4 gap-2">
            <div v-for="i in 4" :key="i" class="w-10 h-10 border rounded flex items-center justify-center">
              {{ password.length >= i ? '●' : '' }}
            </div>
          </div>
        </div>
      </div>
      <van-number-keyboard
        :show="true"
        @input="onInput"
        @delete="onDelete"
        :maxlength="4"
      />
    </van-popup>

    <!-- 搜索区域 -->
    <div class="p-3">
      <div class="flex gap-2 mb-2">
        <van-button 
          :type="searchForm.gender === '' ? 'primary' : 'default'" 
          size="small" 
          block 
          @click="searchForm.gender = ''"
        >
          全部
        </van-button>
        <van-button 
          :type="searchForm.gender === '男' ? 'primary' : 'default'" 
          size="small" 
          block 
          @click="searchForm.gender = '男'"
        >
          男生
        </van-button>
        <van-button 
          :type="searchForm.gender === '女' ? 'primary' : 'default'" 
          size="small" 
          block 
          @click="searchForm.gender = '女'"
        >
          女生
        </van-button>
      </div>
      <van-search
        v-model="searchForm.name"
        placeholder="请输入姓名"
        @search="handleSearch"
      />
      <van-search
        v-model="searchForm.contact"
        placeholder="请输入手机号"
        @search="handleSearch"
      />
    </div>

    <!-- 列表区域 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="px-3">
          <van-cell-group
            v-for="user in tableData"
            :key="user.id"
            inset
            class="mb-3"
          >
            <van-cell>
              <template #title>
                <div class="flex items-center">
                  <span class="text-lg font-medium">{{ user.name }}</span>
                  <van-tag :type="user.gender === '男' ? 'primary' : 'danger'" class="ml-2">
                    {{ user.gender }}
                  </van-tag>
                </div>
                <div class="mt-1 text-sm text-gray-500">
                  {{ user.birth_year }}年 · {{ user.education }} · {{ user.work_location }}
                </div>
              </template>
              <template #value>
                <div class="text-right">
                  <div class="text-sm text-gray-600">{{ user.occupation }}</div>
                  <div class="mt-1 text-xs text-gray-400">{{ formatDate(user.created_at) }}</div>
                </div>
              </template>
            </van-cell>
            <van-cell>
              <template #title>
                <div class="flex justify-end gap-2">
                  <van-button
                    plain
                    type="primary"
                    size="small"
                    @click="handleView(user)"
                  >
                    查看
                  </van-button>
                  <van-button
                    plain
                    type="warning"
                    size="small"
                    @click="handleEdit(user)"
                  >
                    编辑
                  </van-button>
                  <van-button
                    plain
                    type="danger"
                    size="small"
                    @click="handleDelete(user)"
                  >
                    删除
                  </van-button>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from "vue";
import { showDialog, showToast } from "vant";
import request from "@/utils/request";
import { useRouter } from "vue-router";

// 学历映射
const educationMap = {
  juniorHigh: "初中",
  highschool: "高中",
  college: "大专",
  bachelor: "本科",
  master: "硕士",
  phd: "博士",
};

// 搜索表单
const searchForm = reactive({
  name: "",
  contact: "",
  gender: "",
});

// 监听性别变化
watch(() => searchForm.gender, () => {
  handleSearch();
});

// 列表数据
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 添加密码相关状态
const showKeyboard = ref(false);
const password = ref('');
const isVerified = ref(localStorage.getItem('listVerified') === 'true');

// 获取路由实例
const router = useRouter();

// 处理图片URL
const getFullImageUrl = (url) => {
  if (!url) return "";
  if (url.startsWith("http")) return url;
  return `${import.meta.env.VITE_UPLOAD_URL}${url}`;
};

// 处理密码输入
const onInput = (key) => {
  if (password.value.length < 4) {
    password.value += key;
    if (password.value.length === 4) {
      if (password.value === '9303') {
        isVerified.value = true;
        localStorage.setItem('listVerified', 'true');
        showKeyboard.value = false;
        getList(true);
      } else {
        showToast('密码错误');
        password.value = '';
      }
    }
  }
};

// 处理删除
const onDelete = () => {
  if (password.value.length > 0) {
    password.value = password.value.slice(0, -1);
  }
};

// 获取列表数据
const getList = async (isRefresh = false) => {
  if (!isVerified.value) {
    showKeyboard.value = true;
    return;
  }
  
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm,
    };
    const res = await request({
      url: "/users/list",
      method: "get",
      params,
    });
    // 处理图片URL
    if (res.data.list) {
      res.data.list = res.data.list.map((item) => {
        if (item.photo_urls) {
          item.photo_urls = item.photo_urls.map(getFullImageUrl);
        }
        return item;
      });
    }

    if (isRefresh) {
      tableData.value = res.data.list;
    } else {
      tableData.value = [...tableData.value, ...res.data.list];
    }

    total.value = res.data.total;
    finished.value = tableData.value.length >= total.value;
  } catch (error) {
    console.error("获取列表失败:", error);
    showToast("获取列表失败");
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  tableData.value = [];
  finished.value = false;
  getList(true);
};

// 加载更多
const onLoad = () => {
  if (!loading.value && !finished.value) {
    if (refreshing.value) {
      currentPage.value = 1;
      getList(true);
    } else {
      currentPage.value += 1;
      getList();
    }
  }
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  finished.value = false;
  currentPage.value = 1;
  tableData.value = [];
  getList(true);
};

// 查看详情
const handleView = (row) => {
  router.push(`/user/${row.id}`);
};

// 编辑
const handleEdit = (row) => {
  router.push({
    path: '/signed',
    query: { 
      id: row.id,
      mode: 'edit'
    }
  })
}

// 删除
const handleDelete = (row) => {
  showDialog({
    title: "提示",
    message: "确定要删除该条记录吗？",
    showCancelButton: true,
  }).then(async () => {
    try {
      await request({
        url: `/users/${row.id}`,
        method: "delete",
      });
      showToast("删除成功");
      handleSearch();
    } catch (error) {
      console.error("删除失败:", error);
      showToast("删除失败");
    }
  });
};

// 格式化日期
const formatDate = (date) => {
  if (!date) return "";
  return new Date(date).toLocaleString();
};

// 初始化
getList(true);
</script>

<style>
:root {
  --van-cell-group-inset-padding: 12px;
  --van-cell-group-inset-border-radius: 8px;
  --van-cell-group-title-padding: 16px 16px 8px;
}

.van-cell-group {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.van-tag {
  font-weight: normal;
}

.van-button--small {
  font-size: 13px;
  padding: 0 12px;
  height: 28px;
  line-height: 26px;
}
</style> 